package com.crowdfunding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.crowdfunding.entity.BackRecordCrowdFunding;
import com.crowdfunding.entity.CrowdFunding;
import com.crowdfunding.entity.DreamCrowdfunding;
import com.crowdfunding.entity.RecordCrowdFunding;
import com.crowdfunding.exception.ImageUploadException;
import com.crowdfunding.feign.UploadAdvice;
import com.crowdfunding.mapper.BackRecordCrowdFundingMapper;
import com.crowdfunding.mapper.CrowdFundingMapper;
import com.crowdfunding.mapper.DreamCrowdfundingMapper;
import com.crowdfunding.mapper.RecordCrowdFundingMapper;
import com.crowdfunding.service.ICrowdfundingImageService;
import com.crowdfunding.service.IDreamCrowdfundingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crowdfunding.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoyu
 * @since 2021-07-09
 */
@Service
public class DreamCrowdfundingServiceImpl extends ServiceImpl<DreamCrowdfundingMapper, DreamCrowdfunding> implements IDreamCrowdfundingService {


    @Autowired
    DreamCrowdfundingMapper dreamCrowdfundingMapper;

    @Autowired
    BackRecordCrowdFundingMapper backRecordCrowdFundingMapper;

    @Autowired
    RecordCrowdFundingMapper recordCrowdFundingMapper;
//    @Autowired
//    RecordCrowdFundingMapper recordCrowdFundingMapper;

    @Autowired
    UploadAdvice uploadAdvice;

    @Autowired
    ICrowdfundingImageService imageService;

    @Override
    public List<DreamCrowdfunding> getCrowdFundingList() {

        List<DreamCrowdfunding> list=dreamCrowdfundingMapper.selectList(null);

        return list;
    }

    @Override
    public void add(DreamCrowdfunding crowdFunding) {
        dreamCrowdfundingMapper.insert(crowdFunding);
    }

    @Override
    //开启事物回滚
    @Transactional(rollbackFor = Exception.class)
    public void insertCrowdFunding(DreamCrowdfunding crowdFunding) {
        crowdFunding.setDreamId(UUIDUtils.getUUID());
        dreamCrowdfundingMapper.insert(crowdFunding);
    }

    @Override
    public DreamCrowdfunding selectById(String cfId){
        return dreamCrowdfundingMapper.selectById(cfId);
    }

    @Override
    public  void deleteCrowFunding(String cfId){
        dreamCrowdfundingMapper.deleteById(cfId);
    }

    @Override
    public void updateCrowdFunding(DreamCrowdfunding cF){
        dreamCrowdfundingMapper.updateById(cF);
    }

    @Override
    //开启事物回滚
    @Transactional(rollbackFor = Exception.class)
    public int addAmount(double cfrAmount,String cfId,String username){
        try {
            int result=-1;
            //查询出原有金额
//        crowdFundingMapper.select(new QueryWrapper<>().select("cf_already_amount"))
//        crowdFundingMapper.updateAmount(cfrAmount,cfId);
            DreamCrowdfunding crowdFunding = dreamCrowdfundingMapper.selectOne(new QueryWrapper<DreamCrowdfunding>().eq("dream_id", cfId));
            double Amount=crowdFunding.getDreamAlreadyAmount()+cfrAmount;
            System.err.println(Amount);
            //筹款金额超出总金额，提示并进行多余款项退款
            if (Amount>crowdFunding.getDreamTotalAmount()){

                RecordCrowdFunding crowdFundin=new RecordCrowdFunding();
                crowdFundin.setCfId(cfId).setUsername(username).setCfrAmount(cfrAmount);
                //添加支付记录
                recordCrowdFundingMapper.insert(crowdFundin);

                //添加退款记录
                double backAmount=Amount-crowdFunding.getDreamTotalAmount();
                BackRecordCrowdFunding bkcf=new BackRecordCrowdFunding();
                bkcf.setBCfrAmount(backAmount);
                bkcf.setCfId(cfId);
                bkcf.setUsername(username);
                backRecordCrowdFundingMapper.insert(bkcf);

                //已筹款数额累积,更新数据库
                crowdFunding.setDreamAlreadyAmount(Amount-backAmount);
                dreamCrowdfundingMapper.updateById(crowdFunding);

                result=2;
            }
            else if(Amount<=crowdFunding.getDreamTotalAmount()){
                RecordCrowdFunding crowdFundin=new RecordCrowdFunding();
                crowdFundin.setCfId(cfId).setUsername(username).setCfrAmount(cfrAmount);
                //添加支付记录
                recordCrowdFundingMapper.insert(crowdFundin);

                if (crowdFunding.getDreamTotalAmount()==Amount) {
                    crowdFunding.setStatus(2);
                }

                //已筹款数额累积,更新数据库
                crowdFunding.setDreamAlreadyAmount(Amount);
                dreamCrowdfundingMapper.updateById(crowdFunding);

                result=1;
            }else {
                result=-1;
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }

    }

    @Override
    public DreamCrowdfunding getOneCrowFunding(String cfId){
        return dreamCrowdfundingMapper.selectById(cfId);
    }

    @Override
    public void changeCrowdFundingStatus(String cfId, int status){
        DreamCrowdfunding crowdFunding=new DreamCrowdfunding();
        crowdFunding.setStatus(status);
        dreamCrowdfundingMapper.update(crowdFunding,
                new UpdateWrapper<DreamCrowdfunding>().eq("dream_id",cfId)
        );
    }

    @Override
    public List<DreamCrowdfunding> getCrowdFundingListByuserName(String username){
        List<DreamCrowdfunding> list = dreamCrowdfundingMapper.selectList(new QueryWrapper<DreamCrowdfunding>().eq("username",username));
        return list;
    }

    @Override
    public  List<DreamCrowdfunding> getparticipateList(String username){
        //查询与该用户相关的活动记录
        List<RecordCrowdFunding> recordCrowdFundingList=recordCrowdFundingMapper.selectList(new QueryWrapper<RecordCrowdFunding>().select("dream_id").eq("username",username));
//        System.err.println(recordCrowdFundingList==null);
        //将活动记录中的活动id封装到一个组数中
        if (!recordCrowdFundingList.isEmpty()){
            List<String> cfIdList=new ArrayList<>();
            for (RecordCrowdFunding r: recordCrowdFundingList
            ) {
                cfIdList.add(r.getCfId());
            }
//        cfIdList.forEach(System.err::println);
            //遍历数组查询活动列表
            List<DreamCrowdfunding> crowdFundingList=dreamCrowdfundingMapper.selectBatchIds(cfIdList);
//            crowdFundingList.forEach(System.err::println);
            return crowdFundingList;
        }else {
            return null;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addCrowdFunding(DreamCrowdfunding crowdFunding, MultipartFile[] files) throws Exception {
        String id = UUIDUtils.getUUID();
        crowdFunding.setDreamId(id);
        //第一张不为空，则默认文件数组不为空
        if (!files[0].isEmpty()) {
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files
            ) {
                urls.add(uploadAdvice.getUrl(file));
            }
//                    设置第一张图片为封面图片
            crowdFunding.setDreamImage(urls.get(0));
            // 将所有图片url存库
            imageService.addimages(crowdFunding.getDreamId(), urls);
        } else {
            throw new ImageUploadException("图片上传出错");
        }

        dreamCrowdfundingMapper.insert(crowdFunding);


    }
    }
